﻿using System.IO;
using System.Xml.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MiniHttpd;
using CalcSharp.Core.ServerPackets;

namespace CalcDataServ
{
    class Server
    {
        HttpServer core;
        string[] AlowedAdresses, DenyedAdresses;
        MemoryStream resp;

        public Server()
        {
            resp = new MemoryStream();
            this.core = new HttpServer();
            this.core.LogConnections = (bool)Program.Config["LogConnections"];
            this.core.Timeout = (int)Program.Config["IdleTimeOut"];
            this.core.Port = (int)Program.Config["ServerPort"];
            AlowedAdresses = (string[])Program.Config["AlowAdresses"];
            DenyedAdresses = (string[])Program.Config["DenyAddresses"];
            this.core.ValidRequestReceived += new HttpServer.RequestEventHandler(core_ValidRequestReceived);
        }

        #region Authentication
        private bool IsInRange(string rangeAdress, string addr)
        {
            string[] rS, aS;
            if (rangeAdress.ToLower() == addr.ToLower()) return true;
            rS = rangeAdress.ToLower().Split('.');
            aS = addr.ToLower().Split('.');
            bool res = true;
            for (int i = 0; i < rS.Length; i++)
            {
                if (rS[i] == "*") break;
                else if (rS[i] == aS[i]) res = true;
                else
                {
                    res = false;
                    break;
                }
            }
            return res;
        }

        private bool CanServe(string clientIP)
        {
            bool deny, alow;
            deny = false;
            alow = false;

            if (AlowedAdresses.Length > 1)
            {
                foreach (string addr in AlowedAdresses)
                {
                    if (IsInRange(addr, clientIP))
                    {
                        alow = true;
                        break;
                    }
                }
            }
            else alow = true;
            if (DenyedAdresses.Length > 1)
            {
                foreach (string addr in DenyedAdresses)
                {
                    if (IsInRange(addr, clientIP))
                    {
                        deny = true;
                        break;
                    }
                }
            }
            else deny = false;
            if (!deny && alow) return true;
            else return false;
        }
        #endregion

        private void SerializeToStream(object o, Type t)
        {
            XmlSerializer xs = new XmlSerializer(t);
            if (resp != null)
            {
                resp.Close();
                resp = null;
                GC.Collect();
            }
            resp = new MemoryStream();
            xs.Serialize(resp, o);
            resp.Seek(0, SeekOrigin.Begin);
        }

        void core_ValidRequestReceived(object sender, RequestEventArgs e)
        {
            if (e.Request.Protocol != HttpProtocol.Https)
            {
                e.Request.Response.ResponseCode = "302";
                e.Request.Response.SetHeader("Location", e.Request.Uri.ToString().Replace("http://", "https://"));
                return;
            }

            ErrorPacket err;
            if (e.Request.PostData.Length > 0 && e.Request.Uri.AbsolutePath == "/")
            {
                if (!CanServe(e.Request.Client.RemoteAddress))
                {
                    err = new ErrorPacket(1, "Your IP adress is banned on this server");
                    e.Request.Response.ContentType = "text/xml";
                    SerializeToStream(err, typeof(ErrorPacket));
                    e.Request.Response.ResponseContent = this.resp;
                }
                else
                {
                    try
                    {
                        XmlSerializer xs = new XmlSerializer(typeof(CommandPacket));
                        CommandPacket cmd = (CommandPacket)xs.Deserialize(e.Request.PostData);

                        switch (cmd.Cmd)
                        {
                            case Command.None:
                                break;
                            case Command.ServerVersionInfo:
                                SerializeToStream(ServHelper.GetServerInfoPacket(), typeof(ServerInfo));
                                e.Request.Response.ContentType = "text/xml";
                                e.Request.Response.ResponseContent = this.resp;
                                break;
                            default:
                                break;
                        }

                    }
                    catch (Exception)
                    {
                        err = new ErrorPacket(2, "Invalid command data recived");
                        e.Request.Response.ContentType = "text/xml";
                        SerializeToStream(err, typeof(ErrorPacket));
                        e.Request.Response.ResponseContent = this.resp;
                    }
                }
            }
            else
            {
                try
                {
                    switch (e.Request.Uri.AbsolutePath.ToLower())
                    {
                        case "/":
                            e.Request.Response.WriteText(CalcDataServ.Properties.Resources._default, true);
                            break;
                        case "/versioninfo":
                            SerializeToStream(ServHelper.GetServerInfoPacket(), typeof(ServerInfo));
                            e.Request.Response.ContentType = "text/xml";
                            e.Request.Response.ResponseContent = this.resp;
                            break;
                        case "/list":
                            e.Request.Response.WriteText(ServHelper.HandleListingRequest(e.Request.Uri), false);
                            break;
                        default:
                            if (!e.Request.Uri.AbsolutePath.Contains(".."))
                            {
                                string filepath = e.Request.Uri.AbsolutePath.Replace("/", "\\");
                                if (File.Exists((string)Program.Config["ServerRoot"] + filepath))
                                {
                                    string ext = Path.GetExtension((string)Program.Config["ServerRoot"] + filepath);
                                    ext = ext.Replace(".", "");
                                    if (Program.MimeTypes.ContainsKey(ext)) e.Request.Response.ContentType = Program.MimeTypes[ext];
                                    else e.Request.Response.ContentType = "application/octet-stream";
                                    FileStream rfile = File.OpenRead((string)Program.Config["ServerRoot"] + filepath);
                                    e.Request.Response.ResponseContent = rfile;
                                }
                            }
                            break;
                    }
                }
                catch (Exception ex)
                {
                    err = new ErrorPacket(3, "General error: "+ex.Message);
                    e.Request.Response.ContentType = "text/xml";
                    SerializeToStream(err, typeof(ErrorPacket));
                    e.Request.Response.ResponseContent = this.resp;
                }
            }
        }

        public void RunServer()
        {
            this.core.Start();
        }
    }
}
